#!/bin/sh

config_hash () {
    md5sum $BTSYNC_CONFIG_PATH
}

restarts=0

# Initialize config
ctl init;

# Prepare path for config file
mkdir -p `basename "$BTSYNC_CONFIG_PATH"`

# Configure PID file
touch "$BTSYNC_PID_PATH"
chown ${BTSYNC_UID}:${BTSYNC_GID} "$BTSYNC_PID_PATH"

# Start BTSync and handle reloads based on config file
while true; do

    # Get md5 hash of config file
    _CONFIG_HASH=$(config_hash)

    # Start/Restart BTSync instance
    [ $restarts -eq 0 ] && echo "Going to start BTSync" || echo "Going to restart BTSync #$restarts"

    # In case it was ownering error, lets fix it anyway
    chown -R ${BTSYNC_UID}:${BTSYNC_GID} $(dirname $BTSYNC_CONFIG_PATH);

    s6-svc -u /app/s6/btsync;

    # Until it is running, do constant checkings into config file
    while s6-svstat /app/s6/btsync | grep '^up' >/dev/null 2>&1; do

        # Wait for next check
        sleep $BTSYNC_CONFIG_INTERVAL_CHECK

        # Check if config has changed
        if [ "$(config_hash)" != "$_CONFIG_HASH" ]; then

            # If so, lets break this while
            echo "Configuration has been changed!"

            break
        fi

    done

    # Make sure btsync is down
    s6-svc -t -wd /app/s6/btsync;

    # Increment restart count
    restarts=$((restarts+1));

done
